package com.fymxy.question_bank_management.controller;
import javax.mail.*;
import javax.mail.internet.*;

import java.util.Date;
import java.util.Properties;
public class SendMail {
    //发件人邮箱及密码
    private static String myEmailAccount = "747930242@qq.com";
    private static String myEmailPassword = "sbpqkvywpvsjbaij";

    //stmp服务器地址
    private static String myEmailSMTPHost = "smtp.qq.com";

    // 收件人邮箱
    private String receiveMailAccount;

    //发送内容
    private String content;

    public SendMail(String mail,String content)throws Exception{
        this.receiveMailAccount = mail;
        this.content = content;
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", myEmailSMTPHost);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证


        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getInstance(props);
        // 设置为debug模式, 可以查看详细的发送 log
        session.setDebug(true);

        // 3. 创建一封邮件
        MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount);

        // 4. 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport();


        transport.connect(myEmailAccount, myEmailPassword);

        // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());

        // 7. 关闭连接
        transport.close();
    }
    public MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        message.setFrom(new InternetAddress(sendMail, "东软题库管理系统", "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "亲爱的老师", "UTF-8"));

        // 4. Subject: 邮件主题
        message.setSubject("注册结果回复", "UTF-8");

        // 5. Content: 邮件正文（可以使用html标签）
        message.setContent(this.content, "text/html;charset=UTF-8");
        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }
}
